<template>
  <div class="_upload_img">
    <el-upload
      ref="upload"
      list-type="picture-card"
      :limit="limit"
      :on-progress="onprogress"
      :accept="accept"
      :action="uploadUrl"
      :auto-upload="true"
      :on-success="uploadSuccess"
      :headers="{'authorization':authorization}"
    >
      <div slot="default" class="_slot_text">
        <i class="el-icon-plus" />
        <p class="text">{{ uploadTips }}</p>
      </div>
      <div slot="file" slot-scope="{file}">
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.url"
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
      <div slot="tip" class="el-upload__tip">{{ tips }}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" width="500px;z-index:10000">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'UploadImage',
  props: {
    limit: {
      type: Number,
      default: () => 5
    },
    uploadTips: {
      type: String,
      default: () => '点击上传'
    },
    tips: {
      type: String,
      default: () => '只支持：.jpg、.png格式，大小不超过10M'
    },
    accept: {
      type: String,
      default: () => 'image/jpeg,image/jpg,image/png'
    },
    // 上传图片接口地址
    uploadUrl: {
      type: String,
      default: () => `${process.env.VUE_APP_BASE_API}trafficfly-manager/api/upload/uploadFile`
    },
    // 单图上传,上传第二张图片时会替换第一张图片，用于身份证正反面上传
    single: {
      type: Boolean,
      default: () => false
    },
    // 用于回显的数据
    defaultData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      authorization: getToken()
    }
  },
  watch: {
    defaultData: {
      handler(val) {
        if (val && val.length > 0) {
          this.$refs.upload.uploadFiles = this.defaultData
        }
      }
    }
  },
  mounted() {
    // 回显已上传的照片
    if (this.defaultData && this.defaultData.length > 0) {
      try {
        setTimeout(() => {
          this.$refs.upload.uploadFiles = this.defaultData
        }, 500)
      } catch (error) {
        console.log(error)
      }
    }
  },
  methods: {
    // 删除图片
    handleRemove(file) {
      const { uploadFiles } = this.$refs.upload
      uploadFiles.forEach((item, index) => {
        if (file.uid === item.uid) {
          uploadFiles.splice(index, 1)
        }
      })
      if (uploadFiles.length < 1) return this.$emit('input', null)
      this.$emit('input', JSON.stringify(uploadFiles))
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传成功
    uploadSuccess(res, file, fileList) {
      console.log(res, file, fileList, 'fileListfileListfileList')
      const arr = []
      fileList.forEach(item => {
        const { response } = item
        if (response) {
          const { data } = response.body
          if (data) {
            arr.push({ url: data })
          } else if ((typeof response.body) === 'string') {
            arr.push({ url: response.body })
          }
        } else {
          arr.push({ url: item.url })
        }
      })
      // 抛出原始的fileList
      this.$emit('input', arr)
    },
    // 处理上传单张身份证图片-如果已经上传，再次上传则替换之前的
    onprogress(file) {
      const { uploadFiles } = this.$refs.upload
      if (this.single && uploadFiles.length > 1) {
        uploadFiles.splice(0, 1)
      }
    }
  }
}
</script>
<style lang="scss">
._upload_img {
  ._slot_text {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    .text {
      height: 20px;
      line-height: 20px;
      margin-top: 10px;
    }
  }
}
</style>
